#include "SessionHandler.h"
#include "Controller.h"

#include <iostream>
#include <string.h>

using namespace std;
using namespace resip;

class Controller;


SessionHandler::SessionHandler(Controller* parent) : m_done(false), m_owner(parent)
{
	initialize();
}

SessionHandler::~SessionHandler()
{
	cleanup();
}

void SessionHandler::initialize()
{
}

void SessionHandler::cleanup()
{
}

// Callbacks: InviteSessionHandler

void SessionHandler::onNewSession(ServerInviteSessionHandle h, InviteSession::OfferAnswerType oat, const SipMessage& msg)
{
	cout << ">>SERVER: New session" << endl;

	SdpContents * sdpContents = static_cast<SdpContents*>( msg.getContents() );

	m_sis = h;
}

void SessionHandler::onConnectedConfirmed(InviteSessionHandle h, const SipMessage & msg)
{
	cout << ">>CLIENT: Connection confirmed" << endl;
	m_done = true;
}


void SessionHandler::onAckReceived(InviteSessionHandle h, const SipMessage & msg)
{
	cout << ">>CLIENT: ACK received" << endl;
	m_done = true;
}

void SessionHandler::onOffer(InviteSessionHandle is, const SipMessage &msg, const SdpContents &sdp)
{
	bool result;

	// maak sdp bericht aan
	SdpModule * sdpModule = m_owner->getSdpModule();

	result = sdpModule->acceptSdpOffer(sdp);
	cout << "JAJA WE KOMEN HIER ZE " << endl;
	if(result)
	{
		Data* txt = new Data( (*sdpModule).createSdpOffer().c_str() );

		HeaderFieldValue* hfv = new HeaderFieldValue(txt->data(), txt->size());
		Mime type("application", "sdp");
		SdpContents answer(hfv, type);

		cout << "HOU DEES GOE INT OOG\n";
		answer.encode(cout);
		
		is->provideAnswer(answer);
		m_sis->accept();
	}
	else
	{
		m_sis->reject(480);
	}
}

void SessionHandler::onAnswer(resip::InviteSessionHandle h, const resip::SipMessage& msg, const resip::SdpContents& sdp)
{
	// maak sdp bericht aan
	SdpModule * sdpModule = m_owner->getSdpModule();

	sdpModule->acceptSdpOffer(sdp);

}

void SessionHandler::onOfferRequired(InviteSessionHandle h, const SipMessage &msg)
{
	cout << ">>CLIENT: Offer required" << endl;
}

void SessionHandler::hangup()
{
	if( m_sis.isValid() )
	{
		m_sis->end();
		cout << ">>CLIENT: Session terminated" << endl;
	}

	m_done = true;
}

string SessionHandler::parseContactName(string from)
{
	char* buffer = 0;
	char* result = 0;
	
	buffer = new char[from.size() + 1];
	strcpy(buffer, from.c_str());

	// Filter user

	result = strtok(buffer, ":");
	result = strtok(NULL, "@");

	// Return result

	return string(result);
}
